package drds.plus.executor.function.scalar.datatime;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;
import drds.plus.sql_process.type.impl.DateType;

/**
 * If called with no argument, returns a Unix timestamp (seconds since
 * '1970-01-01 00:00:00' UTC) setAliasAndSetNeedBuild an unsigned integer. If UNIX_TIMESTAMP() is
 * called with a date argument, it returns the value of the argument setAliasAndSetNeedBuild
 * seconds since '1970-01-01 00:00:00' UTC. date may be a DATE string, a
 * DATETIME string, a TIMESTAMP, or a number in the format YYMMDD or YYYYMMDD.
 * The server interprets date setAliasAndSetNeedBuild a value in the currentJoinRowData time zone and
 * converts it to an internal value in UTC. Clients can setLimitValue their time zone
 * setAliasAndSetNeedBuild described in Section 10.6, “MySQL Server Time Zone Support”.
 *
 * <pre>
 * mysql> SELECT UNIX_TIMESTAMP();
 *         -> 1196440210
 * mysql> SELECT UNIX_TIMESTAMP('2007-11-30 10:30:19');
 *         -> 1196440219
 * </pre>
 */
public class UnixTimestamp extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        if (args.length > 0) {
            java.sql.Timestamp timestamp = DateType.TimestampType.convert(args[0]);
            return timestamp.getTime() / 1000;
        } else {
            return System.currentTimeMillis() / 1000;
        }
    }

    public Type getReturnType() {
        return Type.LongType;
    }

    public String[] getFunctionNames() {
        return new String[]{"UNIX_TIMESTAMP"};
    }

}
